//
//  GKStatusViewModel.swift
//  MicroBlogFunc
//
//  Created by GK on 16/4/13.
//  Copyright © 2016年 GK. All rights reserved.
//

import UIKit
import SDWebImage
class GKStatusViewModel: NSObject {

    static let shareInstance: GKStatusViewModel = GKStatusViewModel()
    
    //加载微博数据
    func loadStatus( loadStatusCallBack: ( status: [GKStatus]? , error: NSError?) -> () )  {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let param = [ "access_token" : GKUserAccountViewModel.shareInstance.userAccount!.access_token! ]
        
        //请求微博数据
        GKNetworkTool.shareInstance.GET(urlString, parameters: param, progress: nil, success: { (task, responseObj) in
            
//            GKPrint("请求微博数据成功\(responseObj)")
//            字典转模型
            if let dict = responseObj as? [String : AnyObject],let statusDict = dict["statuses"] as? [[String : AnyObject]]
            {
                var statusModels : [GKStatus] = []
                
                for dict1 in statusDict
                {
                    let status = GKStatus(dict: dict1)
                    statusModels.append(status)
                }
//                loadStatusCallBack(status: statusModels, error: nil)
//                GKPrint(statusModels)
                  //缓存图片
                self.saveWebImg(statusModels, loadStatusCallBack: loadStatusCallBack )
            
            }
            
            
            
            }) { (task, error) in
                
//            GKPrint("请求微博数据失败\(error)")
            loadStatusCallBack(status: nil, error: error)
        }
        
    }
    
    
    //缓存微博图片
    
    private func saveWebImg( statuses : [GKStatus] ,loadStatusCallBack:(statuses : [GKStatus]?,error: NSError? ) -> () ){
        //创建组
        let group = dispatch_group_create()
        //判断每个微博模型是否需要下载图片
        for status in statuses
        {
            var downloadURLs : [NSURL]?
            downloadURLs = status.storePicURLs
            //如果原创微博没有需要下载的图片,判断转发微博是否有图片需要下载
            if downloadURLs == nil
            {
                downloadURLs = status.retweeted_status?.storePicURLs
            }
            
            //判断是否需要下载
            if let urls = downloadURLs
            {
                //只有一张图片的情况需要先下载图片,然后在布局该图片在在微博中的尺寸比例
                if urls.count == 1
                {
                    let url = urls.first
                    dispatch_group_enter(group)
                    
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed:
                { (img, error, _, _, _) in
                            
                    dispatch_group_leave(group)
                    if error != nil
                    {
                        GKPrint("下载单张图片的微博的图片失败")
                        return
                    }
                    GKPrint("下载单张图片的微博的图片成功")
                })
                }
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            
            GKPrint("下载所有单张图片微博图片成功")
            loadStatusCallBack(statuses: statuses, error: nil)
        }
        
        
        
    }
    
    
    
    
}
